<template>
  <div class="vol_meeting">
    <div class="vol_meeting_apply">
      <van-form>
        <van-collapse v-model="collapseActive">
          <base-info
            v-if="showBaseInfo"
            ref="refBaseInfo"
            @updateShape="updateShape"
            @update="updateBaseInfo"
          ></base-info>
          <speaker
            v-if="showSpeaker"
            ref="refSpeaker"
            :is-allow-update="isAllowUpdate"
            :base-info="baseInfo"
            @update="updateSpeaker"
          ></speaker>
          <speaker-price
            v-if="showSpeakerPrice"
            :detail="detail"
            :speaker-list="speakerList"
          ></speaker-price>
          <!-- 会务费用 -->
          <!-- <meeting-price
            ref="refMeetingPrice"
            :speaker-list="speakerList"
          ></meeting-price> -->
          <!-- 会议材料 -->
          <meeting-material
            v-if="showMeetingMaterial"
            ref="refMeetingMaterial"
          ></meeting-material>
          <!-- 线下预算 -->
          <!-- <offline-price
            v-show="shape == 2"
            ref="refOfflinePrice"
            @updatePrice="computedTotalPirceAndNotify"
          ></offline-price> -->
          <!-- 服务费 -->
          <!-- <server-price
            ref="refServerPrice"
            :speaker-list="speakerList"
          ></server-price>  -->
        </van-collapse>
      </van-form>
    </div> 
  </div>

  <base-footer v-if="isAllowUpdate">
    <van-button  type="primary" block @click="clickSubmit">提 交</van-button>
  </base-footer>
</template>

<script setup>
import BaseInfo from './components/base-info.vue'
import Speaker from './components/speaker.vue'
import SpeakerPrice from './components/speaker-price.vue'
import MeetingPrice from './components/meeting-price.vue'
import MeetingMaterial from './components/meeting-material.vue'
import OfflinePrice from './components/offline-price.vue'
import ServerPrice from './components/server-price.vue'
import useUtils from '@/hooks/useUtils'
import { showToast, showConfirmDialog, showNotify, closeNotify } from 'vant'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { ref, inject, onMounted, computed, watch, nextTick } from 'vue'

const { getPrice } = useUtils();
const router = useRouter();
const route = useRoute();
const store = useStore();

const api = inject('api')
const refBaseInfo = ref();
const refSpeaker = ref();
const refMeetingPrice = ref();
const refMeetingMaterial = ref();
const refOfflinePrice = ref();
const speakerList = ref([]);
const detail = ref({})
const stagingId = ref('')
const collapseActive = ref([
  'baseInfo',
  'speaker', 'speakerPrice',
  'meetingPrice',
  'meetingMaterial',
  'offlinePrice',
  'serverPrice'
])

const shape = ref('2')
const baseInfo = ref({})
function updateBaseInfo (data) {
  baseInfo.value = data;
  handleStaging();
}
function updateShape () {
  const baseInfo = refBaseInfo.value.getParams();
  shape.value = baseInfo.shape;
}
const userInfo = computed(() => store.getters['user/getUserInfo'])
// 是否允许编辑修改操作
const isAllowUpdate = computed(() => {
  switch (route.query.handleType) {
    case 'detail': return false;
    default: return true;
  }
})
const showBaseInfo = computed(() => {
  switch (route.query.handleType) {
    case 'settle': return false;
  }
  return true
})
const showSpeaker = computed(() => {
  switch (route.query.handleType) {
    case 'settle': return false;
  }
  return true
})
const showSpeakerPrice = computed(() => {
  switch (route.query.handleType) {
    case 'settle': return false;
  }
  return true
})
// 是否显示会务费用
const showMeetingPrice = computed(() => {
  switch (route.query.handleType) {
    case 'settle': return true;
  }
  return false
})

// 是否显示交会议材料
const showMeetingMaterial = computed(() => {
  switch (route.query.handleType) {
    case 'settle': return true;
  }
  return false;
})

watch(speakerList, (newVal, oldVal) => {
  if (oldVal.length || newVal.length) {
    computedTotalPirceAndNotify()
  }
})

const priceWatch = ref(null)
function clearPriceWatch () {
  if (priceWatch.value) {
    setTimeout(priceWatch.value);
    priceWatch.value = null;
  }
}
// 计算总金额并弹出提示
function computedTotalPirceAndNotify (callback = null) {
  clearPriceWatch();

  // 系统会务组服务费
  const groupServePrice = 0; // 800;
  // 财务服务费
  const financeServePrice = 0; // speakerList.value.length * 85;
  // 讲者税前费用
  const speakerPrice = speakerList
    .value
    .map(item => item.speakerAppearanceFeePretax || 0)
    .reduce((val, item) => val + item, 0)
  // 会务费用
  // const meetingPrice = refOfflinePrice.value?.getTotalPrice() || 0;
  const totalPrice = groupServePrice + financeServePrice + speakerPrice /* + meetingPrice*/;
  
  if (typeof callback === 'function') {
    callback(totalPrice);
  } else {
    priceWatch.value = setTimeout(() => {
      if (route.query.handleType !== 'detail') {
        if (detail.value.state != 4 && totalPrice > userInfo.value.remainingAmount) {
          showNotify({
            type: 'danger',
            message: `费用合计：${getPrice(totalPrice)}，已超出您的余额`,
            duration: 3000
          })
        } else {
          showNotify({
            type: 'primary',
            message: `费用合计：￥${getPrice(totalPrice)}`,
            duration: 3000
          })
        }
      }

      clearPriceWatch();
    }, 500)
  }
}
// 更新讲者信息
function updateSpeaker (val) {
  speakerList.value = []
  val.forEach(item => {
    item.forEach(v => {
      if ((v.speakers || []).length) {
        v.speakers.forEach(val => {
          if (val.speakerId) {
            speakerList.value.push(val)
          }
        })
      }
    })
  })

  handleStaging();
}
// 提交校验
function submitVertify (params = {}) {
  if (route.query.handleType !== 'settle') {
    if (!params.topic) {
      showToast('请输入会议主题');
      return false
    }

    if (!params.startTime) {
      showToast('请选择会议日期');
      return false
    }

    if (!params.shape) {
      showToast('请选择会议形式');
      return false
    }

    // const isExistZx = speakerList.value.some(item => item.speakerRole == 1)
    // if (!isExistZx) {
    //   showToast('请至少添加一位主席');
    //   return false
    // }

    // const isExistTl = speakerList.value.some(item => item.speakerRole == 3)
    // if (!isExistTl) {
    //   showToast('请至少添加一位讨论');
    //   return false
    // }

    // const isExistJz = speakerList.value.some(item => item.speakerRole == 2)
    // if (!isExistJz) {
    //   showToast('请至少添加一位讲者');
    //   return false
    // }

    const isExistNoSettingPrice = (speakerList.value || []).some(item => !item.speakerAppearanceFeeAftertax)
    if (isExistNoSettingPrice) {
      showToast('有讲者还未设置讲课费');
      return false
    }
  } else {
    if ('attach' in params) {
      if (!params.attach.length) {
        showToast('请上传会议现场照片和签到表');
        return false
      }
    }
  }
  return true
}

function save (params) {
  api.meetingApply(params).then(res => {
    if (!res.code) {
      showToast('提交成功')
      router.go(-1)
    }
  })
}

function setRequestParams () {
  let params = {}
  if (refBaseInfo.value) {
    params = refBaseInfo.value.getParams()
  }
  if (refSpeaker.value) {
    params['schedules'] = refSpeaker.value.getParams()
  }

  if (refMeetingMaterial.value) {
    params['attach'] = refMeetingMaterial.value.getParams();
  }
  // params['costs'] = refOfflinePrice.value?.getParams() || [];
  // params.costs.push({ category: 5, budgetFee: (speakerList.value.length || 0) * 85 })
  // params.costs.push({ category: 6, budgetFee: 800 })

  computedTotalPirceAndNotify(totalPrice => {
    params.meetingTotalCost = totalPrice
  })
  
  return params;
}
// 点击提交
function clickSubmit () {
  const params = setRequestParams();
  
  if (!submitVertify(params)) return

  let message = '确定提交申请吗？';
  switch (route.query.handleType) {
    case 'update':
      message = '确定修改并提交申请吗？'
      break;
    case 'settle':
      message = '确定提交结算吗？'
      break;
  }
  showConfirmDialog({
    title: '温馨提示',
    message,
  })
  .then(() => {
    if (route.params.id){
      params.id = route.params.id
    }
    save(params);
  })
  .catch(() => {});
}
let isAllowStaging = true;
// 暂存
function handleStaging() {
  if (!isAllowStaging) return
  const params = setRequestParams();
  if (route.query.handleType == 'update' || !route.query.handleType) {
    if (route.query.handleType == 'update') {
      params.id = route.params.id
    } else if (!route.query.handleType) {
      if (stagingId.value) {
        params.id = stagingId.value
      }
    }
    if(params.topic && params.startTime && params.shape) {
      isAllowStaging = false
      api.meetingTemporary(params, { hideLoading: true }).then(res => {
        isAllowStaging = true
        
        if (!res.code) {
          stagingId.value = res.data
        }
      }).catch(() => {
        isAllowStaging = true
      })
    }
  }
}

function getDetail() {
  if (!route.params.id) return
  isAllowStaging = false
  api.meetingDetail(route.params.id).then(res => {
    if (!res.code) {
      detail.value = res.data

      refBaseInfo.value?.setParams(res.data)
      setTimeout(() => {
        refSpeaker.value?.setParams(res.data)
        // refOfflinePrice.value?.setParams(res.data)
        refMeetingPrice.value?.setParams(res.data)
        refMeetingMaterial.value?.setParams(res.data)
        setTimeout(() => {
          isAllowStaging = true
        }, 10 * 1000);
      }, 500)
    }
  })
}
onMounted(() => {
  getDetail()
})
</script>